package com.aqfeel.controllers;

import com.aqfeel.models.Item;
import com.aqfeel.services.ListService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.validation.Valid;

@Controller
@RequestMapping("/list")
public class ListController {
    @Autowired
    private ListService listService;

    @RequestMapping("/")
    public String index(ModelMap model) {
        model.addAttribute("items", listService.getItems());
        return "/views/list.html";
    }

    @RequestMapping("/add")
    public String create(ModelMap model) {
        Item item = new Item();
        model.addAttribute("item", item);
        return "/views/create.html";
    }

    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public String create(@Valid Item item, BindingResult bindingResult, ModelMap model) {
        if (!bindingResult.hasErrors()) {
            try {
                listService.addItem(item);
                return "redirect:/list/";
            } catch (IllegalArgumentException ex) {
                bindingResult.addError(new ObjectError("item", ex.getMessage()));
            }
        }
        return "/views/create.html";
    }
}
